package com.hf.base.shh;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.hf.buildtb.formodel.CallBackJson;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("default")
public abstract class BaseActionGen <T extends BaseForm<E>,Service extends BaseService<T, E>,E> 

extends ActionSupport implements ModelDriven<T>{

	/**
	 * 
	 */
	private Class<T> entityClass;
	private static final long serialVersionUID = 3024356214066236206L;
	T pageEntity ;
	
	public T getPageEntity() {
		return pageEntity;
	}
	public void setPageEntity(T entity) {
		this.pageEntity = entity;
	}
	@Autowired
	Service service;
	protected   Logger logger ;
	
	public BaseActionGen()
	{
		Type type=  getClass().getGenericSuperclass();
		Type[] params =((ParameterizedType)type).getActualTypeArguments(); 
		entityClass =(Class<T>)params[0];
		try {
			pageEntity = entityClass.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger = Logger.getLogger(entityClass);
		
	}
	public void writeJson(Object object) {

		
		try {
			logger.info("开始转换返回结果");
			String json = JSON.toJSONStringWithDateFormat(object,
					"yyyy-MM-dd HH:mm:ss");
			logger.info("返回结果:"+json);
			ServletActionContext.getResponse().setContentType(
					"text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(json);
			//ServletActionContext.getResponse().getWriter().write(returns);
			ServletActionContext.getResponse().getWriter().flush();
			ServletActionContext.getResponse().getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void setAttribute(String attributeName ,Object attributeValue) {
		ServletActionContext.getRequest().setAttribute(attributeName, attributeValue);
	}
	public HttpServletRequest request =ServletActionContext.getRequest();
	 
	 
	public HttpServletResponse response =ServletActionContext.getResponse();

	@Override
	public T getModel() {
		// TODO Auto-generated method stub
		return pageEntity;
	}
	
	public String list()
	{
		try {
			checkList();
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			request.setAttribute("error", e.getMessage());
			return "error";
		}
				 
		int pageSize =  (pageEntity.getPageNum()==0)?10:pageEntity.getPageNum();
		int pageNum = pageEntity.getPageNum()==0?1:pageEntity.getPageNum();
		
		try {
			if (pageEntity.getEntity()==null) {
				pageEntity =	service.getPage(pageSize, pageNum);
			}
			else
			{
				pageEntity = service.getPage(pageEntity.getEntity());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
			request.setAttribute("error", e.getMessage());
			return "error";
		}
		
		return "list";
	}
	
	public void add(){
		
		CallBackJson json = new CallBackJson();
		boolean statusCode =false;
		try {
			try {
				checkAdd();
				
			} catch (Exception e) {
				json.setStatusCode( false);
				json.setMessage(e.getMessage());
				
				logger.error(e);
				return ;			// TODO: handle exception
			}
			
			try {
				
			    statusCode=	service.saveEntity(pageEntity.getEntity());
				json.setStatusCode( statusCode);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				json.setStatusCode( false);
				json.setMessage(e.getMessage());
				logger.error(e);
				return ;
			}
			if (statusCode) {
				json.setMessage("新增成功");
			}
			else
			{
				json.setMessage("新增失败");			
			}
			 			
			
		} finally {
			// TODO: handle finally clause
			writeJson(json);	
		}
		 			
	}
	
	public void findEntityBykey()
	{
		CallBackJson json = new CallBackJson();
		boolean statusCode =false;
		try {
			try {
				checkAdd();
				
			} catch (Exception e) {
				json.setStatusCode( false);
				json.setMessage(e.getMessage());
				
				logger.error(e);
				return ;			// TODO: handle exception
			}
			
			try {
				
			    statusCode=	service.getEntity(pageEntity.getEntity())==null;
				json.setStatusCode( statusCode);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				json.setStatusCode( false);
				json.setMessage(e.getMessage());
				logger.error(e);
				return ;
			}
			if (statusCode) {
				json.setMessage("不存在");
			}
			else
			{
				json.setMessage("存在");			
			}
			 			
			
		} finally {
			// TODO: handle finally clause
			writeJson(json);	
		}		
	}
	public abstract void checkAdd()throws Exception;
	
	public abstract void checkList()throws Exception;
	 	

}
